<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\dao\crud;

use app\dao\BaseDao;
use app\model\crud\QuestionCategoryModel;

/**
 * 题目分类数据访问层
 * Class QuestionCategoryDao
 * @package app\dao\crud
 */
class QuestionCategoryDao extends BaseDao
{
    /**
     * 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return QuestionCategoryModel::class;
    }

    /**
     * 获取分类列表
     * @param array $where
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryList(array $where = [], string $field = '*')
    {
        return $this->search($where)
            ->field($field)
            ->order('sort asc, id desc')
            ->select()
            ->toArray();
    }

    /**
     * 获取树形分类列表
     * @param int $pid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCategoryTree(int $pid = 0)
    {
        $list = $this->search(['status' => 1, 'is_del' => 0])
            ->order('sort asc, id desc')
            ->select()
            ->toArray();

        return $this->buildTree($list, $pid);
    }

    /**
     * 构建树形结构
     * @param array $list
     * @param int $pid
     * @return array
     */
    protected function buildTree(array $list, int $pid = 0): array
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                $children = $this->buildTree($list, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
}

